<template>
    <page-box>
        <template v-slot:header>
            <ask-breadcrumb>
                <template
                    v-for="(item, index) in $getBreadCrumbsName($route.path)"
                >
                    <ask-breadcrumb-item
                        :key="index"
                        v-if="item.path"
                        :to="'/' + item.path"
                        >{{ item.meta.title }}</ask-breadcrumb-item
                    >
                    <ask-breadcrumb-item :key="index" v-else>{{
                        item.meta.title
                    }}</ask-breadcrumb-item>
                </template>
            </ask-breadcrumb>
        </template>
        <page-search-column class="fixed-column">
            <page-search-item class="right">
                <el-button @click="handleReset('ruleForm')">重置</el-button>
                <el-button type="primary" @click="handleSubmit('ruleForm')"
                    >保存</el-button
                >
            </page-search-item>
        </page-search-column>
        <el-form
            :model="formModel"
            :rules="formModelRules"
            label-position="top"
            ref="ruleForm"
            :key="formKey"
        >
            <el-form-item label="宣传图" prop="imgList" class="upload">
                <el-upload
                    multiple
                    ref="pictureUpload"
                    :action="$staticUrl"
                    list-type="picture-card"
                    :auto-upload="true"
                    :file-list="formModel.imgList"
                    :limit="9"
                    :data="uploadData"
                    accept="image/png,image/jpg,image/jpeg"
                    :on-exceed="handleExceed"
                    :before-upload="beforeAvatarUpload"
                    :on-success="handleOnsuccess"
                    :on-change="OnChange"
                >
                    <i slot="default" class="el-icon-plus"></i>
                    <div class="el-upload__tip" slot="tip">
                        最多上传9张图片，图片格式支持jpg、jpeg、png
                    </div>
                    <div slot="file" slot-scope="{ file }">
                        <img
                            class="el-upload-list__item-thumbnail"
                            :src="file.url"
                            alt=""
                        />
                        <span class="el-upload-list__item-actions">
                            <span
                                class="el-upload-list__item-preview"
                                @click="handlePictureCardPreview(file)"
                            >
                                <i class="el-icon-zoom-in"></i>
                            </span>
                            <span
                                v-if="!disabled"
                                class="el-upload-list__item-delete"
                                @click="handleRemove(file)"
                            >
                                <i class="el-icon-delete"></i>
                            </span>
                        </span>
                    </div>
                </el-upload>
            </el-form-item>
            <el-collapse v-model="activeNames">
                <el-collapse-item title="镇基本信息" name="basic" class="basic">
                    <div class="basic-left">
                        <el-form-item label="村数" prop="villageCount">
                            <el-input
                                v-model.number="formModel.villageCount"
                                maxlength="6"
                                placeholder="请填写村数"
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="人口数" prop="population">
                            <el-input
                                v-model.number="formModel.population"
                                maxlength="6"
                                placeholder="请填写人口数"
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="镇编号" prop="number">
                            <el-input
                                v-model="formModel.number"
                                placeholder="请填写镇编号"
                                maxlength="10"
                            ></el-input>
                        </el-form-item>
                        <!-- <el-form-item label="气候" prop="weather">
                            <el-input
                                type="textarea"
                                v-model="formModel.weather"
                                placeholder="请填写乡镇气候"
                                maxlength="200"
                                show-word-limit
                            ></el-input>
                        </el-form-item> -->
                        <!-- <el-form-item label="地理位置" prop="address">
                            <el-input
                                v-model="formModel.address"
                                placeholder="请选择地理位置"
                                readonly
                            >
                                <i
                                    slot="suffix"
                                    class="el-input__icon el-icon-map-location"
                                    @click="selectAddress(mapData)"
                                ></i>
                            </el-input>
                        </el-form-item> -->
                        <!-- <el-form-item label="乡镇特色" prop="feature">
                            <el-input
                                type="textarea"
                                v-model="formModel.feature"
                                maxlength="200"
                                show-word-limit
                                placeholder="请填写乡镇特色亮点"
                            ></el-input>
                        </el-form-item> -->
                    </div>
                    <div class="basic-right">
                        <el-form-item label="户数" prop="houseCount">
                            <el-input
                                v-model.number="formModel.houseCount"
                                placeholder="请填写所辖户数"
                                maxlength="6"
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="经营主体数" prop="enterpriseCount">
                            <el-input
                                v-model.number="formModel.enterpriseCount"
                                placeholder="请填写经营主体数"
                                maxlength="6"
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="特色产业" prop="featuredIndustry">
                            <el-input
                                v-model="formModel.featuredIndustry"
                                placeholder="请填写特色产业"
                            ></el-input>
                            <p class="tips">可以添加最多5个特色产业标签，每个标签用英文逗号","隔开，单个标签最多6个字</p>
                        </el-form-item>
                    </div>
                </el-collapse-item>
                <el-collapse-item title="镇土地信息" name="land" class="basic">
                    <div class="basic-left">
                        <el-form-item
                            label="幅员面积（平方公里）"
                            prop="totalArea"
                        >
                            <el-input
                                v-model="formModel.totalArea"
                                placeholder="请填写幅员面积"
                                maxlength="11"
                            ></el-input>
                        </el-form-item>
                        <el-form-item
                            label="耕地面积（亩）"
                            prop="agriculturalArea"
                        >
                            <el-input
                                v-model="formModel.agriculturalArea"
                                placeholder="请填写耕地面积"
                                maxlength="11"
                            ></el-input>
                        </el-form-item>
                    </div>
                    <div class="basic-right">
                        <el-form-item
                            label="建设用地面积（亩）"
                            prop="buildArea"
                        >
                            <el-input
                                v-model="formModel.buildArea"
                                placeholder="请填写建设用地面积"
                                maxlength="11"
                            ></el-input>
                        </el-form-item>
                        <el-form-item
                            label="已流转耕地面积（亩）"
                            prop="conversionArea"
                        >
                            <el-input
                                v-model="formModel.conversionArea"
                                placeholder="请输入已流转耕地面积"
                                maxlength="11"
                            ></el-input>
                        </el-form-item>
                    </div>
                </el-collapse-item>
                <el-collapse-item title="简介（必填）" name="synopsis">
                    <el-form-item prop="introduction" class="describe">
                        <editor
                            @change="handleChange"
                            :value="formModel.introduction"
                            v-model="formModel.introduction"
                        ></editor>
                    </el-form-item>
                </el-collapse-item>
            </el-collapse>
        </el-form>
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
        <!-- <map-location
            ref="MapLocation"
            @updateAddress="updateAddress"
        ></map-location> -->
    </page-box>
</template>

<script lang="ts">
import { Component, Mixins } from "vue-property-decorator";
import AuthMixin from "@/components/public/upload/auth.mixin.ts";
import { getUUID } from "@/utils";
import MapLocation from "@/components/map-location/index.vue";
import editor from "@/components/public/editor/index.vue";

const validateNum = (rule: any, value: any, callback: any) => {
    const reg = /^([1-9]\d*|[0]{1,1})$/;
    if (value === "") {
        return callback(new Error("不能为空"));
    } else {
        if (isNaN(value)) {
            return callback(new Error("请输入数字类型"));
        } else {
            if (value >= 0) {
                if (reg.test(value)) {
                    callback();
                } else {
                    return callback(new Error("请输入整数"));
                }
            } else {
                return callback(new Error("值不能小于0"));
            }
        }
    }
};

const validateArea = (rule: any, value: any, callback: any) => {
    const reg = /^\d{1,8}$|^\d{1,8}[.]\d{1,2}$/;
    if (value === "") {
        return callback(new Error("不能为空"));
    } else {
        if (isNaN(value)) {
            return callback(new Error("请输入数字类型"));
        } else {
            if (!reg.test(value)) {
                return callback(new Error("面积最大8位整数,2位小数"));
            } else {
                callback();
            }
        }
    }
};
const validateFeaturedIndustry = (rule: any, value: any, callback: any) => {
    const res = value.split(',').filter((item: any) => item);
    const num = res.filter((item: any) => item.length > 6).length;
    if (res.length > 5) {
        return callback(new Error("最多5个特色产业标签"));
    } else if (num) {
        return callback(new Error("单个标签最多6个字"));
    } else {
        callback();
    }
};
interface FormType {
    imgList: any[];
    villageCount: string;
    houseCount: string;
    population: string;
    enterpriseCount: string;
    number: string;
    // weather: string;
    // feature: string;
    totalArea: string;
    agriculturalArea: string;
    buildArea: string;
    conversionArea: string;
    introduction: string;
    featuredIndustry: string;
}

@Component({
    name: "TownExplainNotAlive",
    components: { MapLocation, editor }
})
export default class TownExplain extends Mixins(AuthMixin) {
    // 表单数据
    formModel: FormType = {
        imgList: [],
        villageCount: "",
        houseCount: "",
        population: "",
        enterpriseCount: "",
        number: "",
        // weather: "",
        // address: "",
        // longitude: "",
        // latitude: "",
        // feature: "",
        totalArea: "",
        agriculturalArea: "",
        buildArea: "",
        conversionArea: "",
        introduction: "",
        featuredIndustry: ''
    };

    path = "";

    // 表单验证规则
    formModelRules = {
        imgList: [
            {
                type: "array",
                required: true,
                message: "请上传图片"
            }
        ],
        villageCount: [
            { required: true, message: "请输入所辖村数" },
            { required: true, validator: validateNum }
        ],
        houseCount: [
            { required: true, message: "请输入户数" },
            { required: true, validator: validateNum }
        ],
        population: [
            { required: true, message: "请输入人口数" },
            { required: true, validator: validateNum }
        ],
        enterpriseCount: [
            { required: true, message: "请输入经营主体数" },
            { required: true, validator: validateNum }
        ],
        number: [{ required: true, message: "请输入镇编号" }],
        // weather: [{ required: true, message: "请输入气候" }],
        // address: [{ required: true, message: "请选择地理位置" }],
        // feature: [{ required: true, message: "请输入特色亮点" }],
        totalArea: [
            { required: true, message: "请输入总面积" },
            { required: true, validator: validateArea }
        ],
        agriculturalArea: [
            { required: true, message: "请输入耕地面积" },
            { required: true, validator: validateArea }
        ],
        buildArea: [
            { required: true, message: "请输入建设用地面积" },
            { required: true, validator: validateArea }
        ],
        conversionArea: [
            { required: true, message: "请输入已流转耕地面积" },
            { required: true, validator: validateArea }
        ],
        introduction: [{ required: true, message: "请填写镇的简介" }],
        featuredIndustry: [
            { required: false, validator: validateFeaturedIndustry, trigger: 'blur' }
        ]
    };

    show = false;

    // 上传图片时需要携带的参数
    uploadData: any = {
        signature: "",
        "x-cos-security-token": "",
        "Content-Type": "",
        key: "",
        dir: "",
        host: ""
    };

    // 上传到腾讯云后返回的数据
    sourceList: any[] = [];

    handleTypeId = "";
    formKey = 0;

    activeNames: string[] = ["basic", "land", "synopsis"];
    dialogImageUrl = "";
    dialogVisible = false;
    disabled = false;

    // 地图经纬度和城市名称
    // mapData = {
    //     address: "",
    //     cityAddress: "",
    //     longitude: "",
    //     latitude: ""
    // };

    get State() {
        if (this.handleTypeId) {
            return "IsEdit";
        } else {
            return "IsAdd";
        }
    }

    created() {
        this.getInfo();
    }

    // 表单回显用于修改
    async getInfo() {
        const res = await this.$server["townAndvillage/query"]({ data: {} });
        if (res.data.code === 200 && res.data.data) {
            this.handleTypeId = res.data.data.id;
            this.formModel.villageCount = String(res.data.data.villageCount);
            this.formModel.houseCount = String(res.data.data.houseCount);
            this.formModel.population = String(res.data.data.population);
            this.formModel.enterpriseCount = String(
                res.data.data.enterpriseCount
            );
            this.formModel.number = res.data.data.number;
            // this.formModel.weather = res.data.data.weather;
            // this.formModel.feature = res.data.data.feature;
            this.formModel.totalArea = String(res.data.data.totalArea);
            this.formModel.agriculturalArea = String(
                res.data.data.agriculturalArea
            );
            this.formModel.buildArea = String(res.data.data.buildArea);
            this.formModel.conversionArea = String(
                res.data.data.conversionArea
            );
            this.formModel.introduction = res.data.data.introduction;
            this.formModel.featuredIndustry = res.data.data.featuredIndustry;
            // 初始化图片路径列表用于回显
            const imgList = res.data.data.advertisingMap.split(",");
            const list: any[] = [];
            imgList.forEach((item: any) => {
                list.push({ url: `${item}` });
            });
            this.formModel.imgList = this.formModel.imgList.concat(list);
            this.sourceList = this.sourceList.concat(list);
            this.formModel.imgList = this.formModel.imgList.map((item: any) => {
                return { uid: item.uid, url: `${this.$staticUrl}${item.url}` };
            });
            this.$nextTick(() => {
                this.formModel.imgList.forEach((item: any, i: any) => {
                    this.sourceList[i]._id = item.uid;
                });
            });
        }
    }

    handleChange(val: any) {
        if (val.length > 0) {
            (this.$refs.ruleForm as any).clearValidate("introduction");
        } else {
            (this.$refs.ruleForm as any).validateField("introduction");
        }
    }

    handleRemove(file: any) {
        (this.$refs.pictureUpload as any).handleRemove(file);
        const index = this.sourceList.findIndex(
            (item: any) => item._id === file.uid
        );
        const num = this.formModel.imgList.findIndex(
            (item: any) => item.uid === file.uid
        );
        this.sourceList.splice(index, 1);
        this.formModel.imgList.splice(num, 1);
        if (this.formModel.imgList.length === 0) {
            (this.$refs.ruleForm as any).validateField("imgList");
        }
    }

    handlePictureCardPreview(file: any) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
    }

    // 当图片的个数超出限制时
    handleExceed(files: any, fileList: any) {
        this.$message.warning(
            `当前限制选择 9 个文件，本次选择了 ${
                files.length
            }个文件，共选择了 ${files.length + fileList.length} 个文件`
        );
    }

    handleOnsuccess(response: any, file: any, fileList: any) {
        this.formModel.imgList = fileList;
    }

    OnChange(file: any, fileList: any) {
        if (fileList.length > 0) {
            (this.$refs.ruleForm as any).clearValidate("imgList");
        }
    }

    // 图片上传之前把每张图片上传到腾讯云同时验证格式
    beforeAvatarUpload(file: any) {
        const isTYPE = file.type;
        const fileTypeList = ["image/jpg", "image/png", "image/jpeg"];
        if (!fileTypeList.includes(isTYPE)) {
            this.$message.error("上传图片只能是JPG、PNG、JPEG 格式!");
            return false;
        }
        return new Promise((resolve: any, reject: any) => {
            const _path =
                "/town-village-view/img/" +
                new Date().format("yyyy-MM-dd") +
                "/" +
                this.path;
            this.getAuthorization({ Method: "POST", Pathname: "/" })
                .then((info: any) => {
                    this.uploadData.signature = info.Authorization;
                    this.uploadData["x-cos-security-token"] =
                        info.XCosSecurityToken;
                    this.uploadData["Content-Type"] = "";
                    this.uploadData.key =
                        _path +
                        getUUID() +
                        "." +
                        (file.file
                            ? file.file.type.split("/")[1]
                            : file.type.split("/")[1]);
                    this.uploadData.dir = _path;
                    this.uploadData.host = this.$staticUrl;
                    this.sourceList.push({
                        _id: file.uid,
                        url: this.uploadData.key
                    });
                    resolve(true);
                })
                .catch((err: any) => {
                    this.$message.error({
                        message: err.message || err.content || "接口请求失败",
                        type: "error",
                        duration: 1500
                    });
                    return reject(new Error(err));
                });
        });
    }

    // 提交表单
    handleSubmit(formName: any) {
        const imgList = this.sourceList.map((item: any) => {
            return item.url;
        });
        (this.$refs[formName] as any).validate(async(valid: any) => {
            if (valid) {
                this.formModel.featuredIndustry = this.formModel.featuredIndustry.split(',').filter((item: any) => item).join(",");
                const res = await this.$server["area/form"]({
                    data: {
                        id: this.handleTypeId,
                        advertisingMap: imgList.toString(),
                        // address: this.formModel.address,
                        villageCount: Number(this.formModel.villageCount),
                        houseCount: Number(this.formModel.houseCount),
                        population: Number(this.formModel.population),
                        enterpriseCount: Number(this.formModel.enterpriseCount),
                        number: this.formModel.number,
                        // weather: this.formModel.weather,
                        // longitude: this.formModel.longitude,
                        // latitude: this.formModel.latitude,
                        // feature: this.formModel.feature,
                        totalArea: Number(this.formModel.totalArea),
                        agriculturalArea: Number(
                            this.formModel.agriculturalArea
                        ),
                        buildArea: Number(this.formModel.buildArea),
                        conversionArea: Number(this.formModel.conversionArea),
                        introduction: this.formModel.introduction,
                        featuredIndustry: this.formModel.featuredIndustry
                    }
                });
                if (res.data.code === 200) {
                    this.$message.success("添加成功");
                    // this.sourceList = [];
                } else {
                    this.$message.error(res.data.message);
                }
            } else {
                return false;
            }
        });
    }

    handleReset(formName: any) {
        this.formModel.imgList = [];
        this.sourceList = [];
        this.formKey++;
        if (this.handleTypeId) {
            this.getInfo();
        } else {
            (this.$refs[formName] as any).resetFields();
            (this.$refs.pictureUpload as any).clearFiles();
        }
    }
}
</script>

<style lang="scss" scoped>
::v-deep {
    .page-base-body {
        height: calc(100% - 50px) !important;
        background: transparent !important;
    }
    .ask-tinymce-editor-box {
        padding: 0 !important;
    }
}

.el-form {
    padding: 0px 27px 40px 56px;
    margin-top: 10px;
    background: #fff;
    ::v-deep {
        .upload {
            .el-form-item__content {
                line-height: 20px;
            }
            .el-form-item__label {
                padding: 0;
            }
            .el-upload__tip {
                margin-top: 4px;
                color: #9da1a4;
            }
            .el-upload--picture-card {
                width: 105px;
                height: 105px;
                line-height: 120px;
            }
            .el-upload-list--picture-card .el-upload-list__item {
                width: 105px;
                height: 105px;
            }
        }

        .el-form-item {
            margin-bottom: 16px;
            .el-input__suffix-inner {
                color: #de2728;
                font-weight: 600;
                font-size: 18px;
                cursor: pointer;
            }
        }
        .el-collapse {
            border: none;
            .el-form-item__label {
                height: 20px;
                line-height: 20px;
            }

            .describe {
                .el-form-item__content {
                    width: 100%;
                    .el-textarea__inner {
                        height: 300px;
                    }
                }
            }

            .el-form-item__content {
                width: 320px;
                .el-input__inner {
                    height: 30px;
                    line-height: 30px;
                }
                .el-textarea__inner {
                    height: 100px;
                }
            }
            .el-collapse-item__wrap {
                border: none;
            }
            .el-collapse-item__header {
                margin-bottom: 12px;
                line-height: 22px;
                font-size: 16px;
                &.is-active {
                    border-bottom-color: #ebeef5;
                }
            }
            .basic {
                .el-collapse-item__content {
                    display: flex;
                    justify-content: space-between;
                    .basic-left,
                    .basic-right {
                        width: 50%;
                    }
                }
            }
        }
    }
    .tips {
        margin: 0;
        line-height: 22px;
        font-size: 14px;
    }
}
</style>
